package com.example.productdataserviceprovider.service.city;

import cn.hutool.core.thread.ThreadUtil;
import com.example.productdataserviceprovider.service.AbstractService;
import com.example.productdataserviceprovider.service.search.model.SearchResultModel;
import com.example.productdataserviceprovider.service.utils.HttpUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Deprecated
public class LibraryServiceImpl extends AbstractService implements LibraryService {
    @Override
    public Map<String, String> getCitys(String cityFile) {
        Map<String,String> citys=new HashMap<>();
        BufferedReader reader=null;
        try {
            reader=new BufferedReader(new InputStreamReader(new FileInputStream(cityFile),"UTF-8"));
            String line=reader.readLine();
            if(line!=null){
                String[] datas=line.split("、");
                for(String data:datas){
                    citys.put(data,data);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("totalCitysSize="+citys.size());
        return citys;
    }

    @Override
    public Map<String, String> getLibrarysFromFile(String file) {
        Map<String,String> librarys=new HashMap<>();
        BufferedReader reader=null;
        try {
            reader=new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
            String line=null;
            while((line=reader.readLine())!=null){
                //if(line.indexOf("图书馆")!=-1||line.indexOf("文化中心")!=-1||line.indexOf("文化馆")!=-1||line.indexOf("体育管理中心")!=-1){
                    librarys.put(line.trim(),"");
                //}
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("totalSize="+librarys.size());
        return librarys;
    }
    @Override
    public Map<String, String> getLibrarysNameFromFile(String file) {
        Map<String,String> librarys=new HashMap<>();
        BufferedReader reader=null;
        Pattern pattern1=Pattern.compile("（(.*?)）");
        Pattern pattern2=Pattern.compile("\\((.*?)\\)");
        try {
            reader=new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
            String line=null;
            while((line=reader.readLine())!=null){
                if(line.indexOf("图书馆")!=-1){
//                    System.out.println("line="+line);
                    if(line.contains("（")||line.contains("(")){
                        Matcher matcher=pattern1.matcher(line);
                        if(matcher.find()){
                            librarys.put(matcher.group(1),"");
                        }else{
                            matcher=pattern2.matcher(line);
                            if(matcher.find()) {
                                librarys.put(matcher.group(1), "");
                            }
                        }
                    }else
                        librarys.put(line.trim(),"");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("totalSize="+librarys.size());
        return librarys;
    }

    @Override
    public void analysisLibrarys(Map<String, String> citys, String keys, String resultFile) {
        SearchResultModel model=new SearchResultModel();
        List<SearchResultModel> resultList=new ArrayList<>();
        int page=1;
        int total=citys.size();
        int current=0;
        BufferedWriter writer=null;
        String fileKeys=keys.replaceAll("\\/","");
        resultFile=resultFile.replaceAll("\\{\\}",fileKeys);
        CityService cityService=new CityServiceImpl();
        try {
            writer=new BufferedWriter(new FileWriter(new File(resultFile)));
            for(Map.Entry<String,String> city:citys.entrySet())
            {
                String cityName=city.getKey();
                logger.info("cityName="+cityName+",keyWord="+keys);
                current++;
                logger.info("当前值:"+current+",total="+total);
                //if(current<1148)continue;
                model.setKey(keys);
                model.setPage(0);
                model.setUrl("https://www.baidu.com/s?wd="+cityName+"%20"+model.getKey()+"&pn="+model.getPage());
                logger.info("url="+model.getUrl());
                String result="";
                try {
                    result= HttpUtils.doGet(model.getUrl()).replaceAll("(\r\n|\r|\n|\n\r)","");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if(!StringUtils.hasText(result)){
                    logger.info("搜索结果为空");
                    continue;
                }
                //解析URL
                SearchResultModel data= cityService.parseSearchResult(result,keys,cityName);
                if(data!=null){
                    data.setCity(cityName);
                    writer.write(data.getCity() +","+data.getTitle()+","+data.getUrl());
                    writer.newLine();
                    writer.flush();
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally
        {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void composeFiles(List<File> files, File dest,boolean isDelete) {
        BufferedWriter writer=null;
        try {
            writer=new BufferedWriter(new FileWriter(dest));
            for(File file:files) {
                BufferedReader reader=new BufferedReader(new FileReader(file));
                String line=null;
                while((line=reader.readLine())!=null){
                    writer.write(line);
                    writer.newLine();
                    writer.flush();
                }
                writer.flush();
                if(reader!=null)reader.close();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(writer!=null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                for(File file:files){
                    if(isDelete){
                        if(file.exists())file.delete();
                    }
                }
            }
        }

    }

    public static void main(String[] args) {
        LibraryService service=new LibraryServiceImpl();
        String dirPath="D:/library/library2/";
        Map<String,String> librarys=service.getLibrarysFromFile(dirPath+"libraryDatas3.txt");
//        for(Map.Entry<String,String> entity:librarys.entrySet()){
//            System.out.println(entity.getKey());
//        }
        logger.info("librarys.size=={}",librarys.size());
        int librarysCapture=50,totalSize=librarys.size();
        int threadSize=totalSize%librarysCapture==0?totalSize/librarysCapture:totalSize/librarysCapture+1;
        Map<String,String>[] librarysDatas=new HashMap[threadSize];
        for(int i=0;i<threadSize;i++){
            librarysDatas[i]=new HashMap<>();
        }
        int index=0;
        for(Map.Entry<String,String> library:librarys.entrySet()){
            librarysDatas[index%threadSize].put(library.getKey(),"");
            index++;
        }

//        String keyWord="城市书房,邻里图书馆,家庭图书分馆,家庭图书馆";//,社区投递,送书上门,快递到家/借书
//        String keyWord="促进全民阅读的决定,全民阅读实施细则,全民阅读实施方案,全民阅读规划,全民阅读条例,全民阅读";
        String keyWord="免费开放工作实施方案,免费开放工作方案,免费开放实施方案,免费开放方案,免费开放具体实施方案,免费开放管理制度,免费开放管理办法";//2020-05-18
//        String keyWord="疫情,新型冠状病毒";//,社区投递,送书上门,快递到家/借书
//        String keyWord="手机借书,扫码借书,图书转借,文献转借,转借服务";//,社区投递,送书上门,快递到家/借书
        CountDownLatch latch=new CountDownLatch(threadSize);
        dirPath=dirPath+"result/";
        ExecutorService executorService= Executors.newCachedThreadPool();
        for(int i=0;i<threadSize;i++){
            String resultFile=dirPath+"librarysDatas-{}-"+i+".txt";
            logger.info("数量:"+i+",Size="+librarysDatas[i].size());
            LibraryThread thread=new LibraryThread(service,librarysDatas[i],keyWord,resultFile,latch);
            executorService.submit(thread);
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.info("开始合并文档===================");
        ThreadUtil.sleep(10, TimeUnit.SECONDS);
        String[] keys=keyWord.split(",");
        for(String key:keys){
            List<File> list=new ArrayList<>();
            File dir=new File(dirPath);
            File[] files=dir.listFiles();
            for(File file:files){
                if(file.getName().indexOf("-"+key+"-")!=-1){
                    list.add(file);
                }
            }
            key=key.replaceAll("\\/","");
            File dest=new File(dir.getPath()+File.separator+"librarysDatas-"+key+"-汇总.txt");
            logger.info("dest==="+dest);
            service.composeFiles(list,dest,true);
        }
        executorService.shutdown();
        logger.info("END");
    }
}
